package lvbu.wang.lvbuoperator.http;

import android.content.Context;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import lvbu.wang.lvbuoperator.bean.JsonMessage;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.engine.BleServerConfig;
import lvbu.wang.lvbuoperator.utils.CommonUtil;


public class BleHttpHelpWS {
	private static String tag = "myLog-HtmlHelper";

	public static String getWebsite_ws() {
		if (BleServerConfig.USE_SERVER_MODE == BleServerConfig.Mode.DEBUG) {
			return "http://ws.lvbu.co/";
		} else if (BleServerConfig.USE_SERVER_MODE == BleServerConfig.Mode.RELEASE){
			return "http://ws.lvbu.wang/";
		}
		return "";
	}

	/*
	 * 获取网页源代码
	 */
	public static String getSource(String route, Map<String, Object> queryStrings, boolean autoAuthCode, Context context) {
		return httpPost(route, queryStrings, autoAuthCode, context);
	}

	// ====================== post方法相关 begin =============================

	private static String httpPost(String route, Map<String, Object> queryStrings, boolean autoAuthCode, Context context) {
		Map<String, Object> params = new HashMap<String, Object>();
		if (queryStrings != null) {
			if (queryStrings.size() > 0) {
				for (String name : queryStrings.keySet()) {
					String value = String.valueOf(queryStrings.get(name));
					params.put(name, value);
				}
			}
		}
		if (autoAuthCode == true) {// 自动添加AuthCode==true
			params.put("authCode", getAuthCode(context));
		}
		String urlPath = BleHttpHelpWS.getWebsite_ws() + route;
		String dataString = getRequestData(params, "UTF-8").toString();
		byte[] data = dataString.getBytes();// 获得请求体
		try {
			URL url = new URL(urlPath);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setConnectTimeout(120000); // 设置连接超时时间
			httpURLConnection.setReadTimeout(120000);// 设置读取时间
			httpURLConnection.setDoInput(true); // 打开输入流，以便从服务器获取数据
			httpURLConnection.setDoOutput(true); // 打开输出流，以便向服务器提交数据
			httpURLConnection.setRequestMethod("POST"); // 设置以Post方式提交数据
			httpURLConnection.setUseCaches(false); // 使用Post方式不能使用缓存

			// 设置请求体的类型是文本类型
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			// 设置请求体的长度
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));

			// 获得输出流，向服务器写入数据
			OutputStream outputStream = httpURLConnection.getOutputStream();
			outputStream.write(data);

			int response = httpURLConnection.getResponseCode(); // 获得服务器的响应码
			// LBLog.i(tag, "response=" + response);
			if (response == HttpURLConnection.HTTP_OK) {
				InputStream is = httpURLConnection.getInputStream();

				byte[] bytes = getBytes(is);
				String str = new String(bytes);
				return str;
			} else {
				return JsonMessage.Error;
			}
		} catch (Exception e) {
			// CrashReport.postCatchedException(e);
			return JsonMessage.Error;
		}

	}

	private static StringBuffer getRequestData(Map<String, Object> params, String encode) {

		StringBuffer stringBuffer = new StringBuffer(); // 存储封装好的请求体信息
		try {
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				stringBuffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(), encode)).append("&");
			}
			if (params.size() > 0) {
				stringBuffer.deleteCharAt(stringBuffer.length() - 1); // 删除最后的一个"&"
			}
		} catch (Exception e) {
			e.printStackTrace();
			// CrashReport.postCatchedException(e);
		}
		return stringBuffer;
	}

	private static byte[] getBytes(InputStream is) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = is.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		is.close();
		bos.flush();
		byte[] result = bos.toByteArray();
		return result;
	}

	public static String getAuthCode(Context context) {
		// 在这里写authCode算法
		String token = "lvbu_admin_token";
		String characteristic = BaseActivity.getCharacteristic(context);
		String origin = BaseActivity.getOrigin();
		String guid = UUID.randomUUID() + "";
		String time = (new Date().getTime() + 8 * 3600 * 1000) + "";
		String sign = CommonUtil.MD5("" + token + "|" + guid + "|" + time + "|" + origin + "|" + characteristic + "|" + "lvbu@365.888.999_To_Everyone_fdsafjlqruo047234jdslf0984vcngfasfsdaf" + "").toUpperCase();
		String authCode = "" + token + "|" + guid + "|" + time + "|" + origin + "|" + characteristic + "|" + sign + "";
		return authCode;
	}
	// ====================== post 方法相关 end =============================

}
